﻿#include<iostream>
#include<cstdio>
using namespace std;
typedef int ElemType;
const int MAXSize = 100;
void BubbleSort(int arr[], int n)//双向冒泡排序
{
	int left = 0, right = n - 1,temp;
	bool exchange = false;
	int CompareConut = 0, MoveCount = 0;
	while (left < right) {
		for (int i = left; i < right; i++) {//不能取等号
			CompareConut++;
			if (arr[i] > arr[i + 1])//大的到后面
			{
				temp = arr[i + 1];//交换过程
				arr[i + 1] = arr[i];
				arr[i] = temp;
				exchange = true;
				MoveCount++;
			}
		}
		if (!exchange)//exchange用于判断是否发生交换，如果没有交换则提前终止循环
			break;
		exchange = false;
		right--;
		for (int j = right; j > left; j--)
		{
			CompareConut++;
			if (arr[j] < arr[j - 1]) {//小的到前面
				temp = arr[j];
				arr[j] = arr[j - 1];
				arr[j - 1] = temp;
				MoveCount++;
			}
		}
		left++;
		for (int i = 0; i < n; i++)
			printf(" %d ", arr[i]);
		printf("\n");
	}
	printf("比较次数为：%d\n", CompareConut);//比较次数
	printf("移动次数为：%d\n", MoveCount);//移动次数
	printf("排序结果为:\n");
	for (int i = 0; i < n; i++)
		printf(" %d ", arr[i]);
	printf("\n");
}


int main()
{
	ElemType a[] = { 8, 4, 2, 3, 5, 1, 6, 9, 0, 7 };
	int n = 10;
	BubbleSort(a, 10);
	return 0;
}